#include "LabelModel.h"

int LabelModel::seq = 0;
QList<LabelModelData> LabelModel::_dataList_;

LabelModelData::LabelModelData(const int &seq, const QString &labelName,const QString &labelColor) {
    _seq_ = seq;
    _labelName_ = labelName;
    _labelColor_ = labelColor;
}


QString LabelModelData::labelName() const {
    return _labelName_;
}

QString LabelModelData::labelColor() const {
    return _labelColor_;
}

int LabelModelData::seq() const {
    return _seq_;
}

bool LabelModelData::operator==(const LabelModelData&  labelModelData) const {
    return this->_labelName_ == labelModelData.labelName();
}

QJsonObject LabelModelData::toJsonObject() {
    QJsonObject json;
    json.insert(QStringLiteral("seq"), this->_seq_);
    json.insert(QStringLiteral("labelName"), this->_labelName_);
    json.insert(QStringLiteral("labelColor"), this->_labelColor_);
    return json;
}




QHash<int, QByteArray> LabelModel::roleNames() const {
    QHash<int, QByteArray> roles;
    roles[LabelNameRole] = "labelName";
    roles[LabelColorRole] = "labelColor";
    roles[SeqRole] = "seq";
    return roles;
}


LabelModel::LabelModel(QObject *parent) : QAbstractListModel(parent) {
};

LabelModel::~LabelModel() {}


int LabelModel::rowCount(const QModelIndex &parent) const {
    Q_UNUSED(parent);
    return _dataList_.count();
}


QVariant LabelModel::data(const QModelIndex &index, int role) const {
    int row = index.row();

    if(row < 0 || row >= _dataList_.count()) {
        return QVariant();
    }
    const LabelModelData &labelModelData = _dataList_[row];
    switch(role) {
        case LabelNameRole:
            return labelModelData.labelName();
            break;
        case LabelColorRole:
            return labelModelData.labelColor();
            break;
        case SeqRole:
            return labelModelData.seq();
            break;
    }
    return QVariant();
}


void LabelModel::insert(int index, const LabelModelData &data) {
    if(index < 0 || index > _dataList_.count()) {
        return;
    }

    emit beginInsertRows(QModelIndex(), index, index);
    _dataList_.insert(index, data);
    emit endInsertRows();
    saveDataList2Local();
    //    emit countChanged(m_data.count());
}

BaseResult::JsonResult LabelModel::remove(const QString &labelName) {
    QT_TRY {
        QList<LabelModelData>::ConstIterator it = _dataList_.constBegin();

        for(int i = 0; i < _dataList_.count(); i++) {
            if(_dataList_[i].labelName() == labelName) {
                this->remove(i);
                break;
            }
        }

        return BaseResult(BaseResult::SUCCEED, "删除成功").toJson();
    } QT_CATCH(QString &e) {
        qDebug() << e << Qt::endl;
        return BaseResult(BaseResult::FAILED, e).toJson();
    }
}


void LabelModel::remove(int index) {
    if(index < 0 || index >= _dataList_.count()) {
        return;
    }

    beginRemoveRows(QModelIndex(), index, index);
    _dataList_.removeAt(index);
    endRemoveRows();
    saveDataList2Local();
}


BaseResult::JsonResult LabelModel::append(const QString &labelName,const QString &labelColor) {
    QT_TRY {
        if(this->_savePath_.isNull() || this->_savePath_.isEmpty()) {
            throw "保存路径为空,请选择!";
        }
        LabelModelData labelModelData(LabelModel::seq++, labelName, labelColor);
        if(isExisted(labelModelData)) {
            return BaseResult(BaseResult::FAILED, "添加失败, 标签已存在").toJson();
        }
        insert(count(), labelModelData);
        saveDataList2Local();
        return BaseResult(BaseResult::SUCCEED, "添加成功").toJson();
    } QT_CATCH(char const* e) {
        qDebug() << e << Qt::endl;
        return BaseResult(BaseResult::FAILED, e).toJson();
    }
}

int LabelModel::count() const {
    return rowCount(QModelIndex());
}


void LabelModel::setSavePath(const QString &savePath) {
    this->_savePath_ = savePath.mid(8);
    QFile file(this->_savePath_+ "/class.txt");

    emit beginResetModel();
    this->_dataList_.clear();
    if(file.exists()) {
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
              throw "文件打开失败!!!!";
        }
        QTextStream stream(&file);
        stream.setEncoding(QStringConverter::Utf8);
        QString line;
        while(!stream.atEnd()) {
            line = stream.readLine();
            QStringList qStringList = line.split(':');
            QT_TRY {
                LabelModelData labelModelData(qStringList[0].toInt(), qStringList[1], qStringList[2]);
                this->_dataList_.append(labelModelData);
            } QT_CATCH(char const* e) {
                continue;
            }
        }
    }
    emit endResetModel();
}


int LabelModel::saveDataList2Local() {
    QFile file(this->_savePath_ + "/class.txt");
    if(file.open(QIODevice::WriteOnly)) {
        QTextStream stream(&file);
        stream.setEncoding(QStringConverter::Utf8);
        for(int i = 0; i < _dataList_.count(); i++) {
            const LabelModelData &labelModelData = _dataList_[i];
            stream << labelModelData.seq() << ":" << labelModelData.labelName() << ":" << labelModelData.labelColor() << "\n" ;
        }
        return 1;
    } else {
        throw "文件打开失败!";
    }
}

bool LabelModel::isExisted(const LabelModelData& labelModeData) {
    bool flag = false;
    for(int i = 0; i < _dataList_.count(); i++) {
        if (labelModeData ==_dataList_[i]) {
             flag = true;
             break;
        }
    }
    return flag;
}

BaseResult::JsonResult LabelModel::get(const int &index) {
    if(!this->_dataList_.empty()) {
        return BaseResult(BaseResult::SUCCEED, "获取成功", this->_dataList_[index].toJsonObject()).toJson();
    } else {
        return BaseResult(BaseResult::FAILED, "获取失败").toJson();
    }

}


LabelModelData LabelModel::getFromSeq(int seq) {
    QList<LabelModelData>::ConstIterator it = _dataList_.constBegin();

    for(int i = 0; i < _dataList_.count(); i++) {
        if(_dataList_[i].seq() == seq) {
            return _dataList_[i];
        }
    }
    throw "no seq label : "  + QString::number(seq);
}



